package com.ktgj.flight.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.*;
import com.ktgj.flight.domain.*;
import com.ktgj.flight.domain.InterfaceEntity.MoOrderPayRequest;
import com.ktgj.flight.domain.InterfaceEntity.MoOrderPayResponse;
import com.ktgj.flight.domain.vo.*;
import com.ktgj.flight.mapper.*;
import com.ktgj.flight.service.IFinanceConsignPymtRecordService;
import com.ktgj.flight.service.IFlightService;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.BankCardApi;
import com.ktgj.pay.api.domain.BankPayInfoApi;
import com.ktgj.pay.api.domain.CustomerApi;
import com.ktgj.pay.api.domain.YeeBaoResultApi;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.flight.domain.FinanceConsignPymtRecord;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 财务机票代收款记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-06-13
 */
@Service
public class FinanceConsignPymtRecordServiceImpl implements IFinanceConsignPymtRecordService
{
    @Autowired
    private FinanceConsignPymtRecordMapper financeConsignPymtRecordMapper;
    @Autowired
    private FlightOrderInfoMapper flightOrderInfoMapper;
    @Autowired
    private RemoteCustomerService remoteCustomerService;
    @Autowired
    private FlightOrderChangeMapper flightOrderChangeMapper;
    @Autowired
    private FlightOrderInfoTicketsMapper flightOrderInfoTicketsMapper;
    @Autowired
    private RemotePayService remotePayService;
    @Autowired
    private FinanceConsignPymtLogMapper financeConsignPymtLogMapper;
    @Autowired
    private IFlightService flightService;

    /**
     * 查询财务机票代收款记录
     * 
     * @param consignPymtRecordId 财务机票代收款记录ID
     * @return 财务机票代收款记录
     */
    @Override
    public FinanceConsignPymtRecord selectFinanceConsignPymtRecordById(Long consignPymtRecordId)
    {
        return financeConsignPymtRecordMapper.selectFinanceConsignPymtRecordById(consignPymtRecordId);
    }

    /**
     * 查询财务机票代收款记录列表
     * 
     * @param financeConsignPymtRecord 财务机票代收款记录
     * @return 财务机票代收款记录
     */
    @Override
    public List<FinanceConsignPymtRecord> selectFinanceConsignPymtRecordList(FinanceConsignPymtRecord financeConsignPymtRecord)
    {
        return financeConsignPymtRecordMapper.selectFinanceConsignPymtRecordList(financeConsignPymtRecord);
    }

    /**
     * 新增财务机票代收款记录
     * 
     * @param financeConsignPymtRecord 财务机票代收款记录
     * @return 结果
     */
    @Override
    public int insertFinanceConsignPymtRecord(FinanceConsignPymtRecord financeConsignPymtRecord)
    {
        return financeConsignPymtRecordMapper.insertFinanceConsignPymtRecord(financeConsignPymtRecord);
    }

    /**
     * 修改财务机票代收款记录
     * 
     * @param financeConsignPymtRecord 财务机票代收款记录
     * @return 结果
     */
    @Override
    public int updateFinanceConsignPymtRecord(FinanceConsignPymtRecord financeConsignPymtRecord)
    {
        return financeConsignPymtRecordMapper.updateFinanceConsignPymtRecord(financeConsignPymtRecord);
    }

    /**
     * 批量删除财务机票代收款记录
     * 
     * @param consignPymtRecordIds 需要删除的财务机票代收款记录ID
     * @return 结果
     */
    @Override
    public int deleteFinanceConsignPymtRecordByIds(Long[] consignPymtRecordIds)
    {
        return financeConsignPymtRecordMapper.deleteFinanceConsignPymtRecordByIds(consignPymtRecordIds);
    }

    /**
     * 删除财务机票代收款记录信息
     * 
     * @param consignPymtRecordId 财务机票代收款记录ID
     * @return 结果
     */
    @Override
    public int deleteFinanceConsignPymtRecordById(Long consignPymtRecordId)
    {
        return financeConsignPymtRecordMapper.deleteFinanceConsignPymtRecordById(consignPymtRecordId);
    }

    /**
     * 代收记录列表
     * */
    @Override
    public TmpFlightOrderInfoVo flightOrderInfoList(FinanceConsignPymtRecordIdVo financeConsignPymtRecordIdVo) {
        TmpFlightOrderInfoVo tmpFlightOrderInfoVo = new TmpFlightOrderInfoVo();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (financeConsignPymtRecordIdVo.getDept() != null && financeConsignPymtRecordIdVo.getDept() != 0){
            Map<String, Object> map = new HashMap<>();
            map.put("deptId", financeConsignPymtRecordIdVo.getDept());
            List<Long> longList = remoteCustomerService.employeeVipIdList(map);
            financeConsignPymtRecordIdVo.setEmployeeId(longList);
        }

        List<Long> idList = new ArrayList<>();
        List<FinanceConsignPymtRecord> financeConsignPymtRecords = financeConsignPymtRecordMapper.financeConsignPymtRecordIdList();
        if (financeConsignPymtRecords != null && financeConsignPymtRecords.size() > 0){
            for (FinanceConsignPymtRecord financeConsignPymtRecord : financeConsignPymtRecords) {
                idList.add(financeConsignPymtRecord.getOrderId());
            }
//            financeConsignPymtRecordIdVo.setId(idList);
        }
        else {
            return null;
        }

        List<Long> ids = new ArrayList<>();
        if (financeConsignPymtRecordIdVo.getStates() != null && financeConsignPymtRecordIdVo.getStates().size() > 0){
            List<FlightOrderChange> flightOrderChanges = flightOrderChangeMapper.flightOrderChangeList(financeConsignPymtRecordIdVo);
            for (FlightOrderChange flightOrderChange : flightOrderChanges) {
                ids.add(Long.valueOf(flightOrderChange.getOrderId()));
            }
        }

        List<Long> tmpIds = new ArrayList<>();
        if (ids.size() > 0){
            for (Long aLong : idList) {
                for (Long id : ids) {
                    if (id == aLong){
                        tmpIds.add(aLong);
                    }
                }
            }
        }
        else {
            tmpIds = idList;
        }

        financeConsignPymtRecordIdVo.setId(tmpIds);
        List<FlightOrderInfo> flightOrderInfos = flightOrderInfoMapper.financeConsignPymtRecordIdList(financeConsignPymtRecordIdVo);
        tmpFlightOrderInfoVo.setTotal(flightOrderInfos.size());
        if (flightOrderInfos.size() > 0){
            for (FlightOrderInfo flightOrderInfo : flightOrderInfos) {
                flightOrderInfo.setOrderNum(flightOrderInfo.getOrderId().toString());

                if (flightOrderInfo.getGuestPymtStsId() != null && flightOrderInfo.getGuestPymtStsId().equals("cancelled")){
                    flightOrderInfo.setGuestPymtStsId("取消");
                }
                else if (flightOrderInfo.getGuestPymtStsId() != null && flightOrderInfo.getGuestPymtStsId().equals("payd")){
                    flightOrderInfo.setGuestPymtStsId("已付");
                }
                else if (flightOrderInfo.getGuestPymtStsId() != null && flightOrderInfo.getGuestPymtStsId().equals("waitPay")){
                    flightOrderInfo.setGuestPymtStsId("等待支付");
                }
                else if (flightOrderInfo.getGuestPymtStsId() != null && flightOrderInfo.getGuestPymtStsId().equals("failPay")){
                    flightOrderInfo.setGuestPymtStsId("支付失败");
                }

                List<FlightOrderInfoTickets> flightOrderInfoTickets = flightOrderInfoTicketsMapper.journeyRescheduled(flightOrderInfo.getOrderId());
                if (flightOrderInfoTickets != null && flightOrderInfoTickets.size() > 0){
                    flightOrderInfo.setFlightNum(flightOrderInfoTickets.get(0).getFlight());
                    if (flightOrderInfoTickets.get(0).getDepartureTime() != null){
                        flightOrderInfo.setDepartureTime(format.format(flightOrderInfoTickets.get(0).getDepartureTime()));
                    }
                }

                List<FlightOrderChange> flightOrderChanges = flightOrderChangeMapper.queryFlightOrderChangeByOrderId(flightOrderInfo.getOrderId().toString());
                if (flightOrderChanges.size() > 0){
                    if (flightOrderChanges.get(0).getChangeType() != null && flightOrderChanges.get(0).getChangeType().equals("change")){
                        flightOrderInfo.setCancellationAndChange("改签");
                    }
                    else if (flightOrderChanges.get(0).getChangeType() != null && flightOrderChanges.get(0).getChangeType().equals("refund")){
                        flightOrderInfo.setCancellationAndChange("退");
                    }
                }
            }
        }

        List<FlightOrderInfo> flightOrderInfoList = new ArrayList<>();

        int count = (financeConsignPymtRecordIdVo.getPageNum() - 1) * financeConsignPymtRecordIdVo.getPageSize();
        int num = count + financeConsignPymtRecordIdVo.getPageSize();
        if (num > flightOrderInfos.size()){
            num = flightOrderInfos.size();
        }
        for (int i = count ; i < num ; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", flightOrderInfos.get(i).getEmployeeId());
            Department department = remoteCustomerService.department(map);
            if (department != null){
                flightOrderInfos.get(i).setDeptName(department.getDeptName());
            }

            FinanceConsignPymtRecord financeConsignPymtRecord = financeConsignPymtRecordMapper.payType(flightOrderInfos.get(i).getOrderId());
            if (financeConsignPymtRecord != null){
                flightOrderInfos.get(i).setPayType(financeConsignPymtRecord.getPymtType());
                flightOrderInfos.get(i).setStatus(financeConsignPymtRecord.getPayStart());
            }

            flightOrderInfoList.add(flightOrderInfos.get(i));
        }
        tmpFlightOrderInfoVo.setFlightOrderInfoList(flightOrderInfoList);
        return tmpFlightOrderInfoVo;
    }

    /**
     * 查询待修改的订单支付信息
     * */
    @Override
    public UpdatePayTypeVo updatePayTypeVo(String orderNum) throws Exception {
        FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.journeyFlightOrderInfo(Long.valueOf(orderNum));
        if (flightOrderInfo != null){
            UpdatePayTypeVo updatePayTypeVo = new UpdatePayTypeVo();
            updatePayTypeVo.setOrderNum(orderNum);
            updatePayTypeVo.setAmount(flightOrderInfo.getPayAmount()==null?"0":flightOrderInfo.getPayAmount().toString());
            R<Long> longR = remoteCustomerService.selectAvailableGoldByCustomerId(flightOrderInfo.getCustomerId());
            if (longR.getData() != null){
                updatePayTypeVo.setReserveMoney(longR.getData().toString());
            }
            else {
                updatePayTypeVo.setReserveMoney("0");
            }

            List<FlightOrderInfoTickets> flightOrderInfoTicketsList = flightOrderInfoTicketsMapper.journeyRescheduled(flightOrderInfo.getOrderId());
            if (flightOrderInfoTicketsList != null && flightOrderInfoTicketsList.size() > 0){
                List<UpdatePayVo> updatePayVoList = new ArrayList<>();
                for (FlightOrderInfoTickets flightOrderInfoTickets : flightOrderInfoTicketsList) {
                    UpdatePayVo updatePayVo = new UpdatePayVo();
                    updatePayVo.setId(flightOrderInfoTickets.getOrderInfoTicketsId());
                    updatePayVo.setTicketNo(flightOrderInfoTickets.getTicketNo());
                    updatePayVoList.add(updatePayVo);
                }
                updatePayTypeVo.setUpdatePayVoList(updatePayVoList);
            }

            return updatePayTypeVo;
        }
        else {
            throw new Exception("无效的订单号");
        }
    }

    /**
     * 保存订单支付信息
     * */
    @Transactional
    @Override
    public int savePay(HttpServletRequest request, UpdatePayTypeVo updatePayTypeVo) throws Exception {
        String token = request.getHeader("token");
        R<Employee> loginEmployeeByToken = remoteCustomerService.getLoginEmployeeByToken(token);
        if (loginEmployeeByToken.getData() == null){
            throw new Exception(loginEmployeeByToken.getMsg());
        }

        FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.journeyFlightOrderInfo(Long.valueOf(updatePayTypeVo.getOrderNum()));
        if (updatePayTypeVo.getUseReservedMoney() != null &&
                !updatePayTypeVo.getUseReservedMoney().equals("") &&
                !updatePayTypeVo.getUseReservedMoney().equals("0")){
            flightOrderInfo.setPayAmount(new BigDecimal(updatePayTypeVo.getActualAmount()));
            flightOrderInfo.setDepositAmount(new BigDecimal(updatePayTypeVo.getUseReservedMoney()));
        }

        flightOrderInfo.setGuestMemo(updatePayTypeVo.getRemark());
        flightOrderInfo.setPayType(updatePayTypeVo.getPayType());
        BankCard bankCard = remoteCustomerService.backCardNum(updatePayTypeVo.getCardNumber());
        if (bankCard != null){
            flightOrderInfo.setPayCardId(bankCard.getBankCardId().toString());
        }
        else {
            BankCard card = new BankCard();
            card.setCardholder(updatePayTypeVo.getCardholder());
            card.setCardNumber(updatePayTypeVo.getCardNumber());
            if (updatePayTypeVo.getCreditCardTime() != null && updatePayTypeVo.getCvv2() != null){
                card.setCardType(EmHelper.cardType.CREDIT_CARD.getValue());
                card.setCvv2(Long.valueOf(updatePayTypeVo.getCvv2()));
                card.setCreditCardTime(updatePayTypeVo.getCreditCardTime());
            }
            else {
                card.setCardType(EmHelper.cardType.DEBIT_CARD.getValue());
            }
            card.setObligatePhone(updatePayTypeVo.getContractPhoneOne());
            card.setMemberId(flightOrderInfo.getCustomerId());

            Map<String, Object> map = new HashMap<>();
            map.put("cardNumber", updatePayTypeVo.getCardNumber());
            BankApi bankApi = remoteCustomerService.bankNames(map);
            if (bankApi != null){
                card.setBankName(bankApi.getBankName());
                card.setBankId(bankApi.getBankId());
            }
            else {
                throw new Exception("无效的银行卡");
            }
            int id = remoteCustomerService.bankCard(card);
            if (id > 0){
                flightOrderInfo.setPayCardId(String.valueOf(id));
            }
            else {
                throw new Exception("新增银行卡失败");
            }
        }

        int i = flightOrderInfoMapper.updateFlightOrderInfo(flightOrderInfo);
        if (i > 0 && updatePayTypeVo.getUpdatePayVoList() != null && updatePayTypeVo.getUpdatePayVoList().size() > 0){
            for (UpdatePayVo updatePayVo : updatePayTypeVo.getUpdatePayVoList()) {
                i = flightOrderInfoTicketsMapper.backfillTicketNumber(updatePayVo.getId(), updatePayVo.getTicketNo());
                if (i <= 0){
                    throw new Exception("票号修改失败,id:" + updatePayVo.getId() + ",票号:" + updatePayVo.getTicketNo());
                }
            }
        }
        return i;
    }

    /**
     * 追加备注
     * */
    @Override
    public AppendRemarksVo appendRemarks(Long orderId, String remark) throws Exception {
        AppendRemarksVo appendRemarksVo = new AppendRemarksVo();
        FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.journeyFlightOrderInfo(orderId);
        List<FlightOrderInfoTickets> flightOrderInfoTickets = flightOrderInfoTicketsMapper.checkTheTicketList(orderId);
        if (flightOrderInfo == null){
            throw new Exception("无效订单号");
        }
        R<Customer> customerInfo = remoteCustomerService.getCustomerInfo(flightOrderInfo.getCustomerId());
        if (customerInfo.getData() == null){
            throw new Exception(customerInfo.getMsg());
        }
        R<Long> longR = remoteCustomerService.selectAvailableGoldByCustomerId(flightOrderInfo.getCustomerId());
        if (longR.getData() == null){
            longR.setData(0l);
        }
        CustomerIdVoApi customerIdVoApi = new CustomerIdVoApi();
        customerIdVoApi.setCustomerId(flightOrderInfo.getCustomerId());
        customerIdVoApi = remoteCustomerService.customerIdApi(customerIdVoApi);

        //备注不为空，先修改后查询
        if (remark != null && !remark.equals("")){
            //原备注有值，进行拼接
            if (flightOrderInfo.getGuestMemo() != null && !flightOrderInfo.getGuestMemo().equals("")){
                flightOrderInfo.setGuestMemo(flightOrderInfo.getGuestMemo() + " " + remark);
            }
            //原备注无值，进行替换
            else {
                flightOrderInfo.setGuestMemo(remark);
            }
            int i = flightOrderInfoMapper.updateFlightOrderInfo(flightOrderInfo);
            if (i <= 0){
                throw new Exception("备注追加失败");
            }
        }

        //备注为空，第一次调用接口，直接查询数据
        appendRemarksVo.setOrderNum(orderId.toString());
        if (customerIdVoApi != null){
            appendRemarksVo.setCustomerName(customerIdVoApi.getCustomerName());
            appendRemarksVo.setCustomerType(customerIdVoApi.getCustomerCardType());
        }

        //订单使用预留款，支付总金额 = 应付金额 + 预留款使用数量
        if (flightOrderInfo.getDepositAmount() != null &&
                flightOrderInfo.getDepositAmount().equals("") &&
                flightOrderInfo.getDepositAmount().compareTo(new BigDecimal(0)) != 0){
            if (flightOrderInfo.getDepositAmount() == null){
                flightOrderInfo.setDepositAmount(new BigDecimal(0));
            }

            BigDecimal payAmount = flightOrderInfo.getPayAmount().add(flightOrderInfo.getDepositAmount());
            appendRemarksVo.setPayAmount(payAmount.toString());
        }
        //订单不使用预留款，支付总金额 = 应付金额
        else {
            appendRemarksVo.setPayAmount(flightOrderInfo.getPayAmount().toString());
        }

        appendRemarksVo.setHandleAmount(flightOrderInfo.getPayAmount().toString());

        //预留款不为零，剩余预留款金额 = 总预留款 - 预留款使用数量
        if (longR.getData() != 0){
            BigDecimal money = new BigDecimal(longR.getData());
            if (flightOrderInfo.getDepositAmount() == null){
                flightOrderInfo.setDepositAmount(new BigDecimal(0));
            }
            BigDecimal reserveMoney = money.subtract(flightOrderInfo.getDepositAmount());
            appendRemarksVo.setReserveMoney(reserveMoney.toString());
        }
        //预留款为零，剩余预留款金额 = 0
        else {
            appendRemarksVo.setReserveMoney("0");
        }
        appendRemarksVo.setName(flightOrderInfo.getContactName());
        appendRemarksVo.setCustomerCode(customerInfo.getData().getCustCertificateNo());
        appendRemarksVo.setPhone(flightOrderInfo.getContactMobile());
        appendRemarksVo.setDescribe(flightOrderInfo.getGuestMemo());

        List<PassengerVo> passengerVoList = new ArrayList<>();
        for (FlightOrderInfoTickets flightOrderInfoTicket : flightOrderInfoTickets) {
            PassengerVo passengerVo = new PassengerVo();
            passengerVo.setName(flightOrderInfoTicket.getGuestName());
            passengerVo.setId(flightOrderInfoTicket.getOrderInfoTicketsId());
            passengerVo.setType(flightOrderInfoTicket.getGuestType());
            passengerVo.setLicenseNum(flightOrderInfoTicket.getGuestIdno());
            passengerVo.setFlight(flightOrderInfoTicket.getFlight());
            passengerVo.setCabinSeat(flightOrderInfoTicket.getCabin());
            if (flightOrderInfoTicket.getTicketPrice() != null){
                passengerVo.setFare(flightOrderInfoTicket.getTicketPrice().toString());
            }
            if (flightOrderInfoTicket.getAirportFee() != null){
                passengerVo.setInfrastructure(flightOrderInfoTicket.getAirportFee().toString());
            }
            if (flightOrderInfoTicket.getFuelFee() != null){
                passengerVo.setFuel(flightOrderInfoTicket.getFuelFee().toString());
            }

            passengerVo.setVoyage(flightOrderInfoTicket.getDeparture() + "-" + flightOrderInfoTicket.getArrival());
            passengerVoList.add(passengerVo);
        }
        appendRemarksVo.setPassengerVoList(passengerVoList);

        List<FinanceConsignPymtLog> financeConsignPymtLogList = new ArrayList<>();
        List<FinanceConsignPymtRecord> financeConsignPymtRecords = financeConsignPymtRecordMapper.selectOrderIdList(flightOrderInfo.getOrderId());
        if (financeConsignPymtRecords.size() > 0){
            for (FinanceConsignPymtRecord financeConsignPymtRecord : financeConsignPymtRecords) {
                FinanceConsignPymtLog financeConsignPymtLog = financeConsignPymtLogMapper.selectById(financeConsignPymtRecord.getConsignPymtRecordId());
                if (financeConsignPymtLog != null){
                    financeConsignPymtLogList.add(financeConsignPymtLog);
                }
            }
        }
        appendRemarksVo.setFinanceConsignPymtLogList(financeConsignPymtLogList);
        return appendRemarksVo;
    }

    /**
     * 网络处理
     * */
    @Override
    public String networkProcessing(HttpServletRequest request, UpdatePayTypeVo updatePayTypeVo) throws Exception {
        FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.journeyFlightOrderInfo(Long.valueOf(updatePayTypeVo.getOrderNum()));
        if (flightOrderInfo != null){
            BankPayInfoApi bankPayInfo = new BankPayInfoApi();
            bankPayInfo.setJsjOrderId(updatePayTypeVo.getOrderNum());
            bankPayInfo.setMoneyAmout(updatePayTypeVo.getActualAmount());
            bankPayInfo.setPayType(updatePayTypeVo.getPayWay());
            R<Customer> customerInfo = remoteCustomerService.getCustomerInfo(flightOrderInfo.getCustomerId());
            CustomerApi customerApi = new CustomerApi();
            if (customerInfo.getData() != null){
                BeanUtils.copyProperties(customerInfo.getData(),  customerApi);
                bankPayInfo.setCustomer(customerApi);
            }
            else {
                throw new Exception(customerInfo.getMsg());
            }
            BankCard bankCard = remoteCustomerService.selectBankCardBytBankCardId(Long.valueOf(flightOrderInfo.getPayCardId()));
            if (bankCard == null){
                throw new Exception("未查到银行卡信息");
            }
            BankCardApi card = new BankCardApi();

            YeeBaoResultApi yeeBaoResultApi;
            //信用卡
            if (updatePayTypeVo.getPayType().equals(BusinessTypeConstants.BankCredit.getValue())){
                if (bankCard.getCardType().equals(BusinessTypeConstants.BankCredit.getValue())){
                    BeanUtils.copyProperties(bankCard, card);
                    Map<String, Object> map = new HashMap<>();
                    map.put("cardNumber", card.getCardNumber());
                    String backCard = remoteCustomerService.backCard(map);
                    card.bankCode = backCard + "CREDIT";
                    bankPayInfo.setCard(card);
                }
                else {
                    throw new Exception("卡类型错误");
                }
                yeeBaoResultApi = remotePayService.CreditSale(bankPayInfo);
            }
            //借记卡
            else if (updatePayTypeVo.getPayType().equals(BusinessTypeConstants.BankDebit.getValue())){
                if (bankCard.getCardType().equals(BusinessTypeConstants.BankDebit.getValue())){
                    BeanUtils.copyProperties(bankCard, card);
                    bankPayInfo.setCard(card);
                }
                else {
                    throw new Exception("卡类型错误");
                }
                yeeBaoResultApi = remotePayService.DebitSale(bankPayInfo);
            }
            else {
                throw new Exception("无效的支付类型");
            }

            if (yeeBaoResultApi.getCode().equals("1")){
                int i;
                try {
                    i = insertFinanceConsighPymtRecord(flightOrderInfo, updatePayTypeVo, request, yeeBaoResultApi);
                } catch (Exception e){
                    throw new Exception(e.getMessage());
                }

                flightOrderInfo.setGuestPymtStsId("payd");
                int info = flightOrderInfoMapper.updateFlightOrderInfo(flightOrderInfo);
                if (info <= 0){
                    throw new Exception("状态修改失败");
                }

                MoOrderPayRequest moRequest = new MoOrderPayRequest();
                moRequest.OrderID = updatePayTypeVo.getOrderNum();
                MoOrderPayResponse response = flightService.payOrder(moRequest);

                FinanceConsignPymtRecord financeConsignPymtRecord = new FinanceConsignPymtRecord();
                financeConsignPymtRecord.setOrderId(Long.valueOf(updatePayTypeVo.getOrderNum()));
                financeConsignPymtRecord.setPayStart("true");
                financeConsignPymtRecordMapper.updatePayStart(financeConsignPymtRecord);

                if (i > 0){
                    return "支付成功";
                }
                else {
                    throw new Exception("交易日志添加失败");
                }
            }
            else {
                return yeeBaoResultApi.getErrorMsg();
            }
        }
        else {
            throw new Exception("无效的订单号");
        }
    }

    /**
     * 新增财务机票代收款记录/交易日志
     * */
    public int insertFinanceConsighPymtRecord(FlightOrderInfo flightOrderInfo, UpdatePayTypeVo updatePayTypeVo, HttpServletRequest request, YeeBaoResultApi yeeBaoResultApi) throws Exception {
        Date date = new Date();
        String token = request.getHeader("token");
        R<Employee> loginEmployeeByToken = remoteCustomerService.getLoginEmployeeByToken(token);
        if (loginEmployeeByToken.getData() != null){
            FinanceConsignPymtRecord financeConsignPymtRecord = new FinanceConsignPymtRecord();
            financeConsignPymtRecord.setOrderId(flightOrderInfo.getOrderId());
            financeConsignPymtRecord.setEmployeeId(loginEmployeeByToken.getData().getEmployeeId());
            financeConsignPymtRecord.setPaymentTime(date);
            financeConsignPymtRecord.setPaymentAmount(new BigDecimal(updatePayTypeVo.getActualAmount()));
            financeConsignPymtRecord.setPaymentConfirm(loginEmployeeByToken.getData().getEmployeeName());
            financeConsignPymtRecord.setOperationTime(date);
            financeConsignPymtRecord.setPymtType(updatePayTypeVo.getPayType());
            financeConsignPymtRecord.setOrderAmount(new BigDecimal(updatePayTypeVo.getAmount()));
            financeConsignPymtRecord.setCreateTime(date);
            financeConsignPymtRecord.setRemark(updatePayTypeVo.getRemark());
            int i = financeConsignPymtRecordMapper.insertFinanceConsignPymtRecord(financeConsignPymtRecord);
            if (i > 0){
                FinanceConsignPymtLog financeConsignPymtLog = new FinanceConsignPymtLog();
                financeConsignPymtLog.setTrascationamount(new BigDecimal(updatePayTypeVo.getActualAmount()));
                financeConsignPymtLog.setTrascationnumber(yeeBaoResultApi.getTrxId());
                financeConsignPymtLog.setTrascationtime(date);
                financeConsignPymtLog.setConsignPymtRecordId(financeConsignPymtRecord.getConsignPymtRecordId());
                int log = financeConsignPymtLogMapper.insertFinanceConsignPymtLog(financeConsignPymtLog);
                return log;
            }
            else {
                throw new Exception("新增记录失败");
            }
        }
        else {
            throw new Exception(loginEmployeeByToken.getMsg());
        }
    }

    /**
     * 支付记录录入会员名称
     * */
    @Override
    public RecordVo recordCustomerName(Long orderId) throws Exception {
        FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.journeyFlightOrderInfo(orderId);
        if (flightOrderInfo != null){
            CustomerIdVoApi customerIdVoApi = new CustomerIdVoApi();
            customerIdVoApi.setCustomerId(flightOrderInfo.getCustomerId());
            customerIdVoApi = remoteCustomerService.customerIdApi(customerIdVoApi);

            RecordVo recordVo = new RecordVo();
            recordVo.setOrderNum(flightOrderInfo.getOrderId().toString());
            recordVo.setCustomerName(customerIdVoApi.getCustomerName());

            return recordVo;
        }
        else {
            throw new Exception("无效的订单号");
        }
    }

    /**
     * 网络处理回显
     * */
    @Override
    public UpdatePayTypeVo echo(Long orderId) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.journeyFlightOrderInfo(orderId);
        if (flightOrderInfo != null){
            UpdatePayTypeVo updatePayTypeVo = new UpdatePayTypeVo();
            updatePayTypeVo.setOrderNum(orderId.toString());

            BankCard bankCard = null;
            if (flightOrderInfo.getPayCardId() != null){
                bankCard = remoteCustomerService.selectBankCardBytBankCardId(Long.valueOf(flightOrderInfo.getPayCardId()));
            }

            if (bankCard != null){
                updatePayTypeVo.setCardholder(bankCard.getCardholder());
                updatePayTypeVo.setPayType(flightOrderInfo.getPayType());
                updatePayTypeVo.setContractPhoneOne(bankCard.getObligatePhone());
                updatePayTypeVo.setCardNumber(bankCard.getCardNumber());
                if (bankCard.getCardType().equals(EmHelper.cardType.CREDIT_CARD.getValue())){
                    if (bankCard.getCreditCardTime() != null){
                        updatePayTypeVo.setCreditCardTime(format.format(bankCard.getCreditCardTime()));
                    }
                    if (bankCard.getCvv2() != null){
                        updatePayTypeVo.setCvv2(bankCard.getCvv2().toString());
                    }
                }
                updatePayTypeVo.setRemark(flightOrderInfo.getGuestMemo());
                if (flightOrderInfo.getDepositAmount() != null){
                    flightOrderInfo.setDepositAmount(new BigDecimal(0));
                }
                BigDecimal amount = flightOrderInfo.getPayAmount().add(flightOrderInfo.getDepositAmount());
                updatePayTypeVo.setAmount(amount.toString());
                updatePayTypeVo.setActualAmount(flightOrderInfo.getPayAmount().toString());
                return updatePayTypeVo;
            }
            else {
                throw new Exception("未查到银行卡信息");
            }
        }
        else {
            throw new Exception("无效的订单号");
        }
    }
}
